<template>

	<view class="page" :style="{height: (device.windowHeight - device.footerHeight)+'px'}">
		<view class="x-form-container">
			<x-loading></x-loading>
			<u--form :labelStyle="xThemeForm().labelStyle" labelPosition="left" :rules="rules" :model="info"
				labelWidth="80px" ref="form1">
				<u-form-item label="收货人" prop="receiptName" borderBottom ref="item1">
					<u--input v-model="info.receiptName" border="none" clearable="true" placeholder="请输入收货人姓名"></u--input>
				<!-- 	<input type="nickname" @input="onInputReceiptName" placeholder="请输入收货人姓名" :value="info.receiptName"
						class="cell_input" /> -->
				</u-form-item>
				<u-form-item label="手机号" prop="mobile" borderBottom ref="item1">
					<u--input v-model="info.mobile" maxlength="11" type="number" border="none" clearable="true"
						placeholder="可前往个人资料绑定手机号"></u--input>
				</u-form-item>

				<u-form-item label="所在地区" prop="address" borderBottom>
		<!-- 			<u-picker :loading="loading" :defaultIndex="currentIndex" ref="uPicker" keyName="name"
						:columns="list" :show="showPicker" @cancel="showPicker = false" @confirm="changePicker"
						@change="changeHandler"></u-picker> -->
					<!-- <view v-if="info.addressName">{{info.addressName}}</view>
					<view v-else class="tips">请选择</view> -->
					<!-- <u--input v-model="info.addressName" border="none" clearable="true" placeholder="请选择"></u--input> -->
					
					
					<picker mode="region" @change="selectRegion" :value="region">
						<view class="placeholder" v-if="!info.addressName">请选择所在地</view>
						<view class="text" v-else>{{info.addressName}}</view>
					</picker>
					
					
					<!-- <view slot="right" class="location" @click="onLocation">
						<u-icon slot="right" name="arrow-right" :color="xIconColor()"></u-icon>
						<u-icon name="map" size="18" color="#fc4e27"></u-icon>
						<x-location ref="locationRef"></x-location>
					</view> -->
				</u-form-item>

				<u-form-item label="详细地址" prop="addressDetail" borderBottom ref="item1">
					<u--input v-model="info.addressDetail" border="none" clearable="true"
						placeholder="填写楼号单元号门号"></u--input>
				</u-form-item>
				<u-form-item label="默认地址" prop="defaultAddress">
					<u-switch slot="right" v-model="info.defaultAddress" :value="info.defaultAddress" :active-value="1" :inactive-value="0" :activeColor="xThemeColor()"
							inactiveColor="#BBB"></u-switch>
							
				</u-form-item>
			</u--form>
		</view>
		<x-footer>
			<button class="x-btn" style="width:710rpx;border: 'none'; border-radius: 44rpx;" @click="onSub">保存</button>
		</x-footer>
	</view>
</template>

<script>
	import {
		addAddress,getAddress
	} from '@/api/address';
	import {
		getUserPhone,
	} from '@/api/mine.js'

	import {
		mapState
	} from 'vuex'
	import {
		ThemeMixin
	} from "@/mixins/theme/xThemeMixin.js"
	import EventBusMacro from '@/plugins/EventBus/eventBusMacro.js'
	import XLocation from '@/components/location/xLocation.vue'

	export default {
		mixins: [ThemeMixin],
		computed: {
			...mapState(['device', 'userInfo']),
			region:function(){
				if(this.info.addressName != "") {
					const addressArray = this.info.addressName.split(",");
					const province = addressArray[0];
					const city = addressArray[1];
					const district = addressArray[2];
					return [province, city, district]
				}
				return []
			}
		},
		components: {
			XLocation,
		},
		data() {
			return {
				tips: '',
				info: {
					addressDetail: '',
					addressName: '', //省，市，区
					mobile: '',
					receiptName: '',
					defaultAddress: 0
				},
				rules: {
					'receiptName': [{
						type: 'string',
						required: true,
						message: '请填写姓名',
						trigger: ['blur', 'change']
					}],
					'addressDetail': [{
						type: 'string',
						required: true,
						message: '请选择详细住址',
						trigger: ['blur', 'change']
					}],
					'mobile': [{
						validator: (rule, value, callback) => {
							return uni.$u.test.mobile(value);
						},
						type: 'string',
						required: true,
						message: '请填写正确的手机号',
						trigger: ['blur', 'change']
					}, ],
				},
			};
		},

		onPageScroll(e) {
			this.scrollTop = e.scrollTop;
		},
		onReady() {
			// this.initDataPicker();
			// 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
			this.$refs.form1.setRules(this.rules);
		},
		onLoad(option) {
			if (option.info) {
				this.info = JSON.parse(option.info);
				console.log("this.info=", this.info)
				// this.currentArea = this.info.addressPath.split(',')
			}

		},
		methods: {
			onAddressDetail(e) {
				this.info.detail = e.detail.value
			},
			selectRegion(e) {
				this.info.addressName = e.detail.value[0] + ',' + e.detail.value[1] + ',' + e.detail.value[2]
				this.info.addressDetail = ""
				console.log("selectRegion this.info=", this.info, ",e=", e)
			},
			onLocation() {
				this.$refs.locationRef.getUserLocation().then(res => {
					this.info.addressName = res.province + ',' + res.city + ',' + res.district
					// this.info.city = res.city
					this.info.addressDetail = res.detail
					console.log("location res=", res)
				}).catch(error => {
					console.log("error=", error)
				})
			},
			onInputReceiptName(e) {
				this.info.receiptName = e.detail.value
			},
			onInputPhone(e) {
				this.info.mobile = e.detail.value
			},
			getPhoneNumber(e) {
				console.log("e=", e)
				console.log(e.detail.code) // 动态令牌
				console.log(e.detail.errMsg) // 回调信息（成功失败都会返回）
				console.log(e.detail.errno) // 错误码（失败时返回）
				if (e.detail.errMsg === 'getPhoneNumber:ok') {
					this.$showLoading()
					getUserPhone(e.detail.code).then(res => {
						this.$hideLoading()
						console.log("getUserPhone res", res)
						this.info.mobile = res
					}).catch(error => {
						this.$hideLoading()
						this.$TOOLS.UNI.showToast("获取手机号失败")
					})
				} else {
					this.$TOOLS.UNI.showToast('获取手机号失败')
				}
			},
			getIndex(list, id) {
				for (var i = 0; i < list.length; i++) {
					if (list[i].id == id) {
						return i;
					}
				}
			},
			// getAllArea(e) {
			// 	this.loading = true
			// 	getArea('').then(res => {
			// 		this.areaList = res;
			// 		this.list[0] = res;
			// 		this.getCity(this.currentArea[0] ? this.currentArea[0] : '1')
			// 		if (this.currentArea[0]) {
			// 			this.currentIndex[0] = this.getIndex(res, this.currentArea[0])
			// 		}
			// 		this.loading = false

			// 	}).catch(err => {
			// 		this.loading = false
			// 	});
			// },
			// getCity(e) {
			// 	this.loading = true
			// 	getArea(e).then(res => {
			// 		this.list[1] = res[0].children;
			// 		const picker = this.$refs.uPicker;
			// 		picker.setColumnValues(1, res[0].children);
			// 		this.loading = false
			// 		this.getCounty(this.currentArea[1] ? this.currentArea[1] : res[0].children[0].id)
			// 		if (this.currentArea[1]) {
			// 			this.currentIndex[1] = this.getIndex(res[0].children, this.currentArea[1])
			// 		}
			// 	}).catch(err => {
			// 		this.loading = false
			// 	});
			// },
			// getCounty(e) {
			// 	this.loading = true
			// 	getArea(e).then(res => {
			// 		this.list[2] = res[0].children;
			// 		const picker = this.$refs.uPicker;
			// 		picker.setColumnValues(2, res[0].children);
			// 		this.loading = false
			// 		if (this.currentArea[2]) {
			// 			this.currentIndex[2] = this.getIndex(res[0].children, this.currentArea[2])
			// 		}
			// 		this.currentArea = ['', '', '']
			// 	}).catch(err => {
			// 		this.loading = false
			// 	});
			// },
			// changePicker(val) {
			// 	this.showPicker = false;
			// 	this.info.address = val.value[2].id;
			// 	this.info.addressName = val.value[0].name + ',' + val.value[1].name + ',' + val.value[2].name;
			// },
			// 增加地址
			onSub() {
				this.$refs.form1
					.validate()
					.then(res => {
						addAddress(this.info).then(res => {
							if (this.info.defaultAddress) {
								getAddress().then(address => {
									let foundDefaultAddress = false
									for (var i = 0; i < address.length; i++) {
										console.log(i)
										if (address[i].defaultAddress == 1) {
											foundDefaultAddress = true
											uni.setStorageSync('address', address[i]);
											break;
										}
									}
									// 没有默认地址就置为空
									if (!foundDefaultAddress) {
										uni.setStorageSync('address', null);
									}


									this.$events.emit(EventBusMacro.EB_EDIT_ADDRESS_INFO)

									uni.showToast({
										title: '添加成功',
										icon: 'none'
									});
									uni.navigateBack();
								})

							} else {
								this.$events.emit(EventBusMacro.EB_EDIT_ADDRESS_INFO)
								uni.showToast({
									title: '添加成功',
									icon: 'none'
								});
								console.log("this.info=", this.info)
								uni.navigateBack();
							}


						});
					})
					.catch(err => {
						console.log('err', err)
					});
			},

			// initCityData() {
			// 	// 遍历城市js
			// 	const cityData = this.areaList;
			// 	cityData.forEach((item1, index1) => {
			// 		let temp2 = [];
			// 		this.cityLevel1.push(item1);

			// 		let temp4 = [];
			// 		let temp3 = [];
			// 		// 遍历市
			// 		item1.children.forEach((item2, index2) => {
			// 			temp2.push(item2);
			// 			// 遍历区
			// 			item2.children.forEach((item3, index3) => {
			// 				temp3.push(item3);
			// 			})
			// 			temp4[index2] = temp3;
			// 			temp3 = [];
			// 		})
			// 		this.cityLevel3[index1] = temp4;

			// 		this.cityLevel2[index1] = temp2;
			// 	})
			// 	// 选择器默认城市
			// 	this.list.push(this.cityLevel1, this.cityLevel2[0], this.cityLevel3[0][0]);
			// },
			// changeHandler(e) {
			// 	const {
			// 		columnIndex,
			// 		index,
			// 		indexs,
			// 		value,
			// 		values,
			// 		// 微信小程序无法将picker实例传出来，只能通过ref操作
			// 		picker = this.$refs.uPicker
			// 	} = e;


			// 	if (columnIndex === 0) { // 选择第一列数据时
			// 		// 设置第二列关联数据
			// 		// 
			// 		this.getCity(this.list[0][index].id)
			// 		// this.getArea(this.cityLevel1[index].id);
			// 		// picker.setColumnValues(1, this.cityLevel2[index]);
			// 		// 设置第三列关联数据
			// 		// picker.setColumnValues(2, this.cityLevel3[index][columnIndex]);
			// 	} else if (columnIndex === 1) { // 选择第二列数据时
			// 		// 设置第三列关联数据
			// 		this.getCounty(this.list[1][index].id)
			// 		// picker.setColumnValues(2, this.cityLevel3[indexs[0]][index]);
			// 	}
			// },
			// backspacePhone() {
			// 	this.info.phoneNo = this.info.phoneNo.slice(0, -1);
			// },
			// changePhone(e) {
			// 	this.info.phoneNo += e;
			// },
			// sexSelect(e) {
			// 	this.info.sex = e.name;
			// 	this.$refs.form1.validateField('sex');
			// },
			submit() {
				// 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
				this.$refs.form1
					.validate()
					.then(res => {
						uni.$u.toast('校验通过');
						setTimeout(() => {
							uni.$u.route({
								url: 'pages/mine/personal-data/test'
								// url: 'pages/mine/personal-data/index'
							});
						}, 300);
					})
					.catch(errors => {
						uni.$u.toast('校验失败');
					});
			},
			reset() {
				const validateList = ['name', 'sex', 'radiovalue1', ];
				this.$refs.form1.resetFields();
				this.$refs.form1.clearValidate();
				setTimeout(() => {
					this.$refs.form1.clearValidate(validateList);
					// 或者使用 this.$refs.form1.clearValidate()
				}, 10);
			},
			// hideKeyboard() {
			// 	uni.hideKeyboard();
			// }
		}
	};
</script>

<style lang="scss" scoped>
	@import "@/mixins/theme/xTheme.scss";

	.location {
		display: flex;
	}
	
	.phone-number {
		border: 2rpx solid #666;
		border-radius: 10rpx;
		padding: 0 10rpx;
		height: 60rpx;
		background-color: #f8f8f8
	}
	
	.page {
		overflow: hidden;
		scroll: hidden;
		// border-top: 1px solid #AAA;
		background-color: $x-content-background;



		.placeholder {
			color: #808080;
		}

		.container {
			padding: 0px 32rpx;
			margin: 24rpx 24rpx 0;
			background-color: white;
			border-radius: 8rpx;

			.login-title {
				display: block;
				font-size: 18px;
				font-weight: 500;
				color: $u-main-color;
				line-height: 1.2;
			}

			.login-desc {
				font-size: 14px;
				color: $u-tips-color;
				line-height: 1.1;
			}

			.login-form {
				// margin: 0px 0 18px;
			}
		}

		.footer {
			position: fixed;
			border-top: 1px solid #AAA;
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: center;
			padding-top: 8px;
		}
	}

	.picker_placeholder {
		color: #ccc;
	}

	.tips {
		margin-top: 10rpx;
		color: #ccc;
		font-size: 28rpx;
	}
</style>